import { setData } from "../common/mutations";
import { isExpire } from "src/assets/utils";

export { setData };

export function setUserinfo(state, userinfo) {
  setData(state.auth, userinfo);
}

export function logout(state) {
  state.auth.token = "";
}

export function setAccounts(state, accounts) {
  if (accounts.constructor === Object) {
    accounts = [accounts];
  }
  // state.accounts = undefined;
  if (!state.accounts) {
    state.accounts = {};
  }
  accounts.forEach((acc) => {
    if (!state.accounts[acc.accounts_id]) {
      state.accounts[acc.accounts_id] = {};
    }
    for (const key in acc) {
      if (Object.hasOwnProperty.call(acc, key)) {
        state.accounts[acc.accounts_id][key] = acc[key];
      }
    }
  });
  checkAccountExpires(state);
}

export function checkAccountExpires(state) {
  for (const id in state.accounts) {
    if (Object.hasOwnProperty.call(state.accounts, id)) {
      const acc = state.accounts[id];
      if (isExpire(acc.expires_time)) {
        acc.enable = 0;
      }
    }
  }
}
